package com.bluesimon.wbf.usercenter;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ume.school.modules.utils.PageUtils;

import com.bluesimon.wbf.usercenter.entity.User;
import com.bluesimon.wbf.usercenter.enums.UserTypeEnum;

/**
 * Created by Zz on 2018/8/27.
 */
@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    public User getUser(String userId) {
        User u = userRepository.findOne(userId);
        return u;
    }
    
    public User getUserByBizId(Integer bizCode) {
        List<User> temp = userRepository.findByBizId(bizCode);
        if (null != temp && temp.size() > 0) {
            return temp.get(0);
        }
        return null;
    }

    public User getUserByName(String userName) {
        List<User> temp = userRepository.findByUserName(userName);
        if (null != temp && temp.size() > 0) {
            return temp.get(0);
        }
        return null;
    }
    
    /**
     * 查询并分页
     */
    @SuppressWarnings("unchecked")
    public Page<User> findAll(final User condition, String offset, String limit) {        
        @SuppressWarnings("rawtypes")
        Specification specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotEmpty((condition.getRealName()))) {
                    predicates.add(cb.like(root.get("realName"), "%" + condition.getRealName() + "%"));
                }
                if (StringUtils.isNotEmpty((condition.getNickName()))) {
                    predicates.add(cb.like(root.get("nickName"), "%" + condition.getNickName() + "%"));
                }
                if (StringUtils.isNotEmpty((condition.getUserName()))) {
                    predicates.add(cb.like(root.get("userName"), "%" + condition.getUserName() + "%"));
                }
                if (condition.getType()!=null) {
                    if(condition.getType().intValue() == UserTypeEnum.NOT_ADMIN.getValue()){
                        predicates.add(cb.notEqual(root.get("type"), UserTypeEnum.ADMIN.getValue()));
                    }
                    else{
                        predicates.add(cb.equal(root.get("type"), condition.getType()));
                    }
                }
                if (condition.getCheckStatus()!=null) {
                    predicates.add(cb.equal(root.get("checkStatus"), condition.getCheckStatus()));
                }
                if (condition.getStatus()!=null) {
                    predicates.add(cb.equal(root.get("status"), condition.getStatus()));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        PageRequest pr = PageUtils.compositePage(offset, limit, "", "");
        return userRepository.findAll(specification, pr);
    }


    public User login(String userName, String password) {
        List<User> list = userRepository.findByUserNameAndPassword(userName, password);
        if (null != list && list.size() > 0) {
            User u = list.get(0);
            return u;
        }
        return null;
    }

    @Transactional
    public User register(User user) {
        user.setId(UUID.randomUUID().toString());
        user.setBizId(getMaxBizId());
        user = userRepository.saveAndFlush(user);
        return user;
    }
    
    /**
     * 获取最大ID
     */
    @SuppressWarnings("unchecked")
    private Page<User> getMaxBizUser() {
        @SuppressWarnings("rawtypes")
        Specification specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        PageRequest pr = PageUtils.compositePage("1", "1", "bizId", "DESC");
        return userRepository.findAll(specification, pr);
    }
    
    private int getMaxBizId(){
        Page<User> pages = getMaxBizUser();
        if(pages!=null &&pages.hasContent()){
            List<User> list = pages.getContent();
            return list.isEmpty()?1001:list.get(0).getBizId().intValue()+1;
        }
        return 1001;
    }



    @Transactional
    public User update(User user) {
        return userRepository.saveAndFlush(user);
    }
}
